//
//  LBUtilModule.m
//  LBReact
//
//  Created by WuShiHai on 19/5/24.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "LBUtilModule.h"
#import "LBRConstants.h"

#import <LBFoundation/LBFoundation.h>
#import <LBUIKit/LBUIKit.h>

#import <UserNotifications/UserNotifications.h>

@implementation LBUtilModule

RCT_EXPORT_MODULE(util)

RCT_EXPORT_METHOD(checkNotifyPermission:(RCTResponseSenderBlock)callback) {
    beginExecInMainBlock
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 10.0) { //iOS10以上包含iOS10
        UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
        [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
            if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined){
                //未选择;
                callback([[NSArray alloc] initWithObjects:@(0), nil]);
            } else if (settings.authorizationStatus == UNAuthorizationStatusDenied){
                //未授权;
                callback([[NSArray alloc] initWithObjects:@(0), nil]);
            } else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized){
                //已授权;
                callback([[NSArray alloc] initWithObjects:@(1), nil]);
            } else {
                //其他情况；
                callback([[NSArray alloc] initWithObjects:@(0), nil]);
            }
        }];
    } else if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 8.0){ // ios8-ios10
        if ([[UIApplication sharedApplication] currentUserNotificationSettings].types  == UIRemoteNotificationTypeNone) {
            callback([[NSArray alloc] initWithObjects:@(0), nil]);
        }else{
            callback([[NSArray alloc] initWithObjects:@(1), nil]);
        }
    } else {
        //其他系统版本默认为推送开启
        callback([[NSArray alloc] initWithObjects:@(1), nil]);
    }
    endExecInMainBlock
}

RCT_EXPORT_METHOD(gotoSetting) {
    beginExecInMainBlock
    NSURL *targetURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 10.0) {
        if ([[UIApplication sharedApplication] canOpenURL:targetURL]) {
            [[UIApplication sharedApplication] openURL:targetURL
                                               options:@{}
                                     completionHandler:nil];
        }
    } else {
        if ([[UIApplication sharedApplication] canOpenURL:targetURL]) {
            [[UIApplication sharedApplication] openURL:targetURL];
        }
    }
    endExecInMainBlock
}


@end
